package com.ruoyi.framework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.ruoyi.framework.config
 * @ClassName: RestTemplateAutoConfiguration
 * @Description:
 * @Author: czl
 * @Date: 2025/10/30 21:40
 */
@Configuration
public class RestTemplateAutoConfiguration {

    /**
     * 声明RestTemplate服务
     *
     * @return RestTemplate
     */
    @Bean
    public RestTemplate registerTemplate(ClientHttpRequestFactory simileClientHttpRequestFactory) {
        RestTemplate restTemplate = new RestTemplate();
        //配置自定义的message转换器
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        messageConverters.add(new RestTemplateHttpMessageConverter());
        restTemplate.setMessageConverters(messageConverters);
        restTemplate.setRequestFactory(simileClientHttpRequestFactory);
        return restTemplate;
    }

    /**
     * 初始化请求工厂
     *
     * @return SimpleClientHttpRequestFactory
     */
    @Bean
    public SimpleClientHttpRequestFactory getFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(120000);
        factory.setReadTimeout(120000);
        return factory;
    }

    /**
     * 数据转换器
     */
    static class RestTemplateHttpMessageConverter extends MappingJackson2HttpMessageConverter {
        public RestTemplateHttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.TEXT_PLAIN);
            //加入text/html类型的支持
            mediaTypes.add(MediaType.TEXT_HTML);
            // tag6
            setSupportedMediaTypes(mediaTypes);
        }

    }
}
